package com.five.common.util;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.UUID;

/**
 * @ClassName BaseUtil
 * @Author Administrator
 * @Date 2018/12/31 11:26
 * @Version 1.0
 * @Description 基础工具类
 **/
public class BaseUtil {
    private static BaseUtil baseUtil = null;

    private BaseUtil() {
    }

    public static BaseUtil getBaseUtil() {
        if (baseUtil == null) {
            baseUtil = new BaseUtil();
        }
        return baseUtil;
    }

    public String getIntegerTime() {
        /**
         *@MethodName getIntegerTime
         *@Data 2018/12/31 11:32
         *@Author wuxuan
         *@Description 获取当前的整形的时间
         **/
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        return simpleDateFormat.format(new Date());
    }

    public String getToken(String requestMethod, String URL) {
        HttpURLConnection connection = null;
        BufferedReader bf = null;
        StringBuilder sb = null;
        try {
            URL url = new URL(URL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod(requestMethod);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.connect();
            bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            sb = new StringBuilder();
            while ((line = bf.readLine()) != null) {
                sb.append(line).append(System.getProperty("line.separator"));
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bf.close();
            } catch (IOException e) {
                e.printStackTrace();
                connection.disconnect(); // 销毁连接
            }
            return sb.toString();
        }
    }

    /**
     * @parm
     * @Description 获取UUid <br/>
     * 2018年10月17日下午5:29:22 <br/>
     * 作者:wu
     */
    public String getUUid() {
        String uuid = UUID.randomUUID().toString();
        return uuid.replaceAll("\\-", "");
    }

    /**
     * @parm
     * @Description 获取当前时间返回格式化日期, yyyy-MM-dd HH:mm:ss格式 <br/>
     * 2018年10月17日下午5:35:05 <br/>
     * 作者:wu
     */
    public String getFormatTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(new Date());
    }

    /**
     * @parm
     * @Description 获取当前时间, 返回时间的字符串yyyyMMddHHmmss格式 <br/>
     * 2018年10月17日下午5:37:59 <br/>
     * 作者:wu
     */
    public String getNowTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        return df.format(new Date());
    }

    /**
     * @parm min随机数最小值 max随机数最大值
     * @Description 获取某一区间的随机数，不能超过int最大范围 <br/>
     * 2018年10月17日下午5:43:01 <br/>
     * 作者:wu
     */
    public int getRandNum(int min, int max) {
        int randNum = min + (int) (Math.random() * ((max - min) + 1));
        return randNum;
    }

    private static MessageDigest md5 = null;

    static {
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * @parm str 要获取MD5值的字符串
     * @Description 获取指定字符串的MD5 <br/>
     * 2018年10月17日下午6:01:30 <br/>
     * 作者:wu
     */
    public String getMd5(String str) {
        byte[] bs = md5.digest(str.getBytes());
        StringBuilder sb = new StringBuilder(40);
        for (byte x : bs) {
            if ((x & 0xff) >> 4 == 0) {
                sb.append("0").append(Integer.toHexString(x & 0xff));
            } else {
                sb.append(Integer.toHexString(x & 0xff));
            }
        }
        return sb.toString();
    }

    /**
     * @parm string:要截取的字符串,sign:分割的符号
     * @Description 字符串截取返回String组 <br/>
     * 2018年10月17日下午6:12:36 <br/>
     * 作者:wu
     */
    public String[] getStringSplit(String string, String sign) {
        String[] strs = string.split("\\" + sign);
        return strs;
    }

    /**
     * @parm str要截取的字符串, begin开始的位数, end结束的位数
     * @Description 指定位置截取字符串 <br/>
     * 2018年10月17日下午6:25:50 <br/>
     * 作者:wu
     */
    public String getStringDivision(String str, int begin, int end) {
        return str.substring(begin, end);
    }

    /**
     * @parm str要截取的字符串, begin开始字符, end结束字符
     * @Description 获取指定字符之间的字符串 <br/>
     * 2018年10月17日下午6:33:09 <br/>
     * 作者:wu
     */
    public String getStringSection(String str, String begin, String end) {
        int start = str.indexOf(begin) + begin.length();
        int over = str.indexOf(end);
        return str.substring(start, over);
    }

    /**
     * @parm filePath配置文件的全路径(不带文件后缀名), getKey要获取的键值对的Key
     * @Description 读取配置文件的指定Key值 properties默认iso-8859-1编码,自带转码 <br/>
     * 2018年10月25日下午12:22:51 <br/>
     * 作者:wu
     */
    public String getProperties(String filePath, String getKey) {
        ResourceBundle resource = ResourceBundle.getBundle(filePath);
        String str = null;
        try {
            str = new String(resource.getString(getKey).getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * @parm str要格式化的字符串
     * @Description 字符串去{}和""<br/>
     * 2019年1月6日 16:48:23 <br/>
     * 作者:wu
     */
    public String stringFormat(String str) {
        return str.replace("{", "").replace("}", "").replace("\"", "");
    }

    /**
     * @parm request
     * @Description 获取请求的IP地址<br/>
     * 2019年01月07日21:37:54<br/>
     * 作者:wu
     */
    public  String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}